package com.cj.wtrails;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;

public abstract class BaseFragment extends Fragment {

    private Context mContext;
    protected View mRoot;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        int layoutId = getContentLayoutId();
        if (mRoot == null) {
            // 初始化当前的根布局, 但是不在创建时就添加到 container 里面
            mRoot = inflater.inflate(layoutId, container, false);
            // 如果第一次初始化, 创建 mRroot 并且初始化控件
        } else {
            if (mRoot.getParent() != null) {
                // 把当前 Root 从其父控件中移除
                ((ViewGroup) mRoot.getParent()).removeView(mRoot);
            }
        }
        mContext = getContext();
        return mRoot;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        show();
        findView();
        init();
        setListener();
    }

    /**
     * 得到当前界面的资源文件 id
     *
     * @return 资源文件 id
     */
    protected abstract int getContentLayoutId();

    /**
     * TODO<显示数据>
     *
     * @return void
     * @throw
     */
    public abstract void show();

    /**
     * TODO<初始化控件>
     *
     * @return void
     * @throw
     */
    public abstract void findView();

    /**
     * TODO<初始化数据>
     *
     * @return void
     * @throw
     */
    public abstract void init();

    /**
     * TODO<设置监听器>
     *
     * @return void
     * @throw
     */
    public abstract void setListener();


    /**
     * TODO<通过id获取View实例>
     *
     * @param vMain
     * @param id
     * @return T
     * @throw
     */
    @SuppressWarnings("unchecked")
    protected <T extends View> T getViewInstance(View vMain, int id) {
        return (T) vMain.findViewById(id);
    }

    /**
     * 是否已登录
     *
     * @return
     */
    public boolean isLogin() {
        return false;
    }


    @Override
    public void onLowMemory() {
        super.onLowMemory();
        Glide.get(mContext).clearMemory();
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mRoot != null) {
            mRoot = null;
        }
        if (mContext != null) {
            mContext = null;
        }
    }
}